﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Web.Script.Serialization;
namespace Knockout.mods.tutor.service
{
    /// <summary>
    /// Summary description for task
    /// </summary>
    public class task : IHttpHandler
    {
        public class CActionResult
        {
            public string Code;
            public string Message;
            public CActionResult(string code, string message)
            {
                Code = code;
                Message = message;
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json"; // application/json text/plain;
            string action = context.Request.Form["action"];
            string ret = "";

            switch (action)
            {
                case "getTask":
                    ret = getTask();
                    break;
                case "saveTask":
                    string tasks = context.Request.Form["tasks"];
                    ret = saveList(tasks);
                    break;

                default:
                    ret = "{\"message\": \"Invalid Action\"}";
                    break;
            }

            context.Response.Write(ret);
            context.Response.End();
        }

        public string getTask()
        {
            string ret = "[{\"title\":\"Wire the money to Panama\",\"isDone\":true},{\"title\":\"Get hair dye, beard trimmer, dark glasses and \\\"passport\\\" \",\"isDone\":false},{\"title\":\"Book taxi to airport\",\"isDone\":false},{\"title\":\"Arrange for someone to look after the cat\",\"isDone\":false}]";
            //string ret = "[{\"a\":10, \"b\":11},{\"a\":20, \"b\":21}]";
            return ret;
        }
        public string saveList(string tasks)
        {
            var ret = "";
            CActionResult objResult;
            try
            {
                //DeserializeObject
                //var obj = new JavaScriptSerializer().DeserializeObject(tasks);

                objResult = new CActionResult("OK", "Task saved successful!");
                ret = new JavaScriptSerializer().Serialize(objResult);
            }
            catch (Exception e)
            {
                objResult = new CActionResult("ERROR", "Saved has error. " + e.Message);
                ret = new JavaScriptSerializer().Serialize(objResult);
            }
            return ret;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}